package org.mwt.ws.webclient.presentation;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mwt.ws.webclient.business.BusinessException;
import org.mwt.ws.webclient.business.RemoteService;
import org.mwt.ws.webclient.business.WSService;
import org.mwt.ws.webclient.business.XmlRpcService;

public class RemoteCall extends HttpServlet {
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, BusinessException {
        String operation = request.getParameter("operation");
        String statement = request.getParameter("statement");
        String tecnologia = request.getParameter("tecnologia");

        String result = "";

        RemoteService service = null;
        
        if ("XmlRpcCall".equals(tecnologia)) {
            service = new XmlRpcService();
        } else if ("JaxWsCall".equals(tecnologia)) {
            service = new WSService();
        }

        if ("CreateXForm".equals(operation)) {
            result = service.CreateXForm(statement);
        } else if ("CreateInsertCode".equals(operation)) {
            result = service.CreateInsertCode(statement);
        } else if ("CreateUpdateCode".equals(operation)) {
            result = service.CreateUpdateCode(statement);
        }
        /*"CREATE TABLE persona (id INT(10) NOT NULL AUTO_INCREMENT," +
                                          "name VARCHAR(20) NOT NULL," +
                                          "PRIMARY KEY (id));");*/

        request.setAttribute("result", result);
        request.setAttribute("operation", operation);
        request.setAttribute("statement", statement);
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
    } 

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (BusinessException ex) {
            System.out.println(ex.getMessage());
            Logger.getLogger(RemoteCall.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (BusinessException ex) {
            System.out.println(ex.getMessage());
            Logger.getLogger(RemoteCall.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
